# -*- coding:utf-8 -*-
from django.shortcuts import render
from django.contrib.auth import authenticate, login, logout
from .models import Customer, Account
from django.contrib.auth.models import User
from .form import Loginform


from django.shortcuts import redirect
from django.core.exceptions import ObjectDoesNotExist
from django.contrib import messages


def get_customer_id(request):
    username = request.user
    user = User.objects.get(username=username)
    try:
        account = Account.objects.get(user_name=user)
    except ObjectDoesNotExist:
        messages.warning(request, '该用户不隶属于具体客户, 请联系管理员确认帐号信息。', fail_silently=True)
        return False, False
    customer_name = account.owner.customer_name
    customer = Customer.objects.get(customer_name=customer_name)
    customer_id = customer.id
    return customer_id, customer_name


def login_view(request):
    if request.method == 'POST' and request.POST:
        uf = Loginform(request.POST)
        if uf.is_valid():
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                customer_id, customer_name = get_customer_id(request)
                if customer_id:
                    request.session['customerId'] = customer_id
                    request.session['customerName'] = customer_name
                    return redirect('/')
                else:
                    logout(request)
            else:
                messages.warning(request, '输入的用户名或密码不正确', fail_silently=True)
    return render(request, 'accounts/login.html')


def logout_view(request):
    logout(request)
    return render(request, 'accounts/logout.html')


